package com.xoa.controller.sso;

import com.xoa.controller.login.loginController;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.sys.SysInterfaceMapper;
import com.xoa.dao.users.OrgManageMapper;
import com.xoa.dao.users.UserExtMapper;
import com.xoa.dao.users.UserFunctionMapper;
import com.xoa.model.common.SysPara;
import com.xoa.model.common.Syslog;

import com.xoa.model.sys.InterfaceModel;
import com.xoa.model.users.OrgManage;

import com.xoa.model.users.UserOnline;
import com.xoa.model.users.Users;
import com.xoa.service.sys.SysLogService;
import com.xoa.service.users.UsersService;
import com.xoa.util.*;

import com.xoa.util.common.StringUtils;

import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;


import com.xoa.util.sso.CASUtils;
import com.xoa.util.sso.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.ParseException;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xoa.controller.login.loginController.userCountMap;

@Controller
@RequestMapping("/sso")
public class SsoController {

    @Autowired
    private OrgManageMapper orgManageMapper;

    @Resource
    private SysLogService sysLogService;

    @Resource
    private UsersService usersService;

    @Autowired
    private SysParaMapper sysParaMapper;

    @Autowired
    private UserExtMapper userExtMapper;

    @Autowired
    private loginController loginController;

    @Autowired
    UserFunctionMapper userFunctionMapper;
    @Resource
    private SysInterfaceMapper sysInterfaceMapper;

    @RequestMapping("/ssoIndex")
    public String defaultIndex() {
        return null;
    }
    /**
     *用户登录
     */
    @RequestMapping(value = "/ssoLogin", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<Users> ssoLoginEnter(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min

        // 获取企业微信和钉钉登陆判断参数
        String thirdPartyType = request.getParameter("thirdPartyType");

        String loginId="1001";
        Integer h5Login=1;
        String userAgent="pc";
        String password="temp";

        CASUtils casUtils = new CASUtils();
        HttpSession session = request.getSession();
        String targetUrl = casUtils.getBasePath(request);
        /** 判断是否已经登录过 */
        if (casUtils.isLogin(session)) {
            //如果登录,重定向到targetUrl
            response.sendRedirect(targetUrl+"main");
            //如果没有登陆过
        } else {
            //判断票据是否存在
            if (casUtils.hasTicket(request)) {
                //存在就获取Cas登录Url 登录成功后返回票据 */
                LoginUser loginUser = casUtils.getLoginUser(request);
                //判断是否登录过
                if (loginUser.isLogin() ) {
                    /** 写入单页面登录判断标志 */
                    casUtils.login(loginUser, session);
                    String username = loginUser.getAccount();
                    CookiesUtil.setCookie(response,"redisSessionId",request.getSession().getId());
                    Cookie redisSessionCookie = new Cookie("redisSessionId",request.getSession().getId());
                    if (StringUtils.checkNull(loginId)) {
                        List<OrgManage> org = orgManageMapper.queryId();
                        if (org != null && org.size() > 0) {
                            loginId = org.get(0).getOid().toString().trim();
                        }
                    }


                    ToJson<Users> json = new ToJson<Users>(0, null);
                    if (StringUtils.checkNull(username)) {
                        json.setFlag(1);
                        json.setCode(LoginState.LOGINPASSWORDERR);
                        json.setMsg("用户名或用户不存在");
                        return json;
                    }
                    ContextHolder.setConsumerType("xoa" + loginId);
                    Users user = usersService.selectUserAllInfoByName(username, request, loginId, password, h5Login,thirdPartyType);
                    if (user == null) {
                        request.getSession().setAttribute("message", "errOne");
                        json.setMsg("用户名或用户不存在");
                        json.setCode(LoginState.LOGINPASSWORDERR);
                        json.setFlag(1);
                        return json;

                    }

                    List<SysPara> list = sysParaMapper.selectAll();
                    String pd = "";
                    String xts = "";
                    String cz = "";
                    for (SysPara sysPara : list) {
                        if ("SEC_RETRY_BAN".equals(sysPara.getParaName())) {
                            pd = sysPara.getParaValue();
                        }
                        if ("SEC_RETRY_TIMES".equals(sysPara.getParaName())) {
                            xts = sysPara.getParaValue();
                        }
                        if ("SEC_BAN_TIME".equals(sysPara.getParaName())) {
                            cz = sysPara.getParaValue();
                        }
                    }

                    Map<String, String> createMap = new HashMap<String, String>();
                    createMap.put("userid", username);
                    createMap.put("password", password);

                    //获取当前用户的登录日志
                    ToJson<Syslog> modifyPwdLog = sysLogService.getLoginLog(request);
                    if(user.getLastVisitTime()!=null){
                         user.setLastVisitTime(new Date());
                        usersService.updateLoginTime(user);
                    }else{
                        //判断他的size小于等于1，因为在查用户user信息时写入log日志的，因此第一次登录size为1
                        if (modifyPwdLog.getObj()==null||modifyPwdLog.getObj().size()<=1) {
                            json.setCode("FirstLogin");
                        } else {
                            user.setLastVisitTime(new Date());
                            usersService.updateLoginTime(user);
                        }
                    }

                    if (StringUtils.checkNull(loginId)) {
                        List<OrgManage> org = orgManageMapper.queryId();
                        if (org != null && org.size() > 0) {
                            loginId = org.get(0).getOid().toString().trim();
                        }
                    }
                    user.setCompanyId(loginId);
                    //判断用户头像
                    if(StringUtils.checkNull(user.getAvatar())){
                        if(!StringUtils.checkNull(user.getSex())){
                            user.setAvatar(user.getSex());
                        }else{
                            user.setAvatar("0");
                        }

                    }else{
                        if(user.getAvatar().equals("0")||user.getAvatar().equals("1")){
                            if(!StringUtils.checkNull(user.getSex())){
                                user.setAvatar(user.getSex());
                            }else{
                                user.setAvatar("0");
                            }
                        }
                        else{
                            //判断用户头像是否找得到
                            String classpath = this.getClass().getResource("/").getPath();
                            String webappRoot = classpath.replaceAll("WEB-INF/classes/", "ui/img/user/");
                            File file_avtor =new File(webappRoot+user.getAvatar());
                            if(!file_avtor.exists()){
                                user.setAvatar(user.getSex());
                            }
                        }
                    }
                    json.setObject(user);
                    json.setFlag(0);

                    //通过userId查询用户是否存在于静态map中
                    UserOnline userOnline = (UserOnline)userCountMap.get(user.getUserId());
                    //如果不存在
                    if(userOnline==null){
                        //声明一个新的用户在线数据
                        UserOnline userOnlineInfo =new UserOnline();
                        try {
                            String format = DateFormatUtils.formatDate(new Date());
                            Integer nowTime = DateFormatUtils.getNowDateTime(format);
                            userOnlineInfo.setClient((byte)2);
                            userOnlineInfo.setPCtime(nowTime);
                            userOnlineInfo.setPCsid(request.getSession().getId());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {//如果存在
                        if (!userOnline.getPCsid().equals("")) {
                            try {
                                String format = DateFormatUtils.formatDate(new Date());
                                Integer nowTime = DateFormatUtils.getNowDateTime(format);
                                userOnline.setPCtime(nowTime);
                                userCountMap.put(user.getUserId(), userOnline);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                String format = DateFormatUtils.formatDate(new Date());
                                Integer nowTime = DateFormatUtils.getNowDateTime(format);
                                userOnline.setPCtime(nowTime);
                                userOnline.setPCsid(request.getSession().getId());
                                userCountMap.put(user.getUserId(), userOnline);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("paraName", "IM_WINDOW_CAPTION");
                    params.put("paraValue", user.getPara().getParaValue());
                    params.put("loginDateSouse",loginId);//组织id
                    //params.put("LOCALE_SESSION_ATTRIBUTE_NAME", locales);//语言


                    String functionIdStr = userFunctionMapper.getUserFuncIdStr(user.getUserId());
                    params.put("functionIdStr", functionIdStr);

                    List<InterfaceModel> interfaceModels = sysInterfaceMapper.getInterfaceInfo();
                    if (0 == user.getTheme() || null == user.getTheme()) {
                        user.setTheme((byte) Integer.parseInt(interfaceModels.get(0).getTheme()));
                    }

                    String theme = "theme" + user.getTheme();
                    params.put("InterfaceModel", theme);
                    params.put("uid", user.getUid());
                    SessionUtils.putSession(request.getSession(), params,redisSessionCookie);

                    response.sendRedirect(targetUrl+"main");
                } else {
                    //重定向到 获取登出地址
                    response.sendRedirect(casUtils.getLogoutUrl(request));
                }
            } else {
                //票据不存在
                /** 获取登出地址 */
                String loginUrl = casUtils.getLoginUrl(request);
                //重定向到 获取登出地址
                response.sendRedirect(loginUrl);
            }
        }
        return null;
    }

    @RequestMapping("/ssoLogout")
    public String defaultLogout() {
        return null;
    }


    @RequestMapping(value = "/powerLogin", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<Users> powerLoginEnter(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min

        // 获取企业微信和钉钉登陆判断参数
        String thirdPartyType = request.getParameter("thirdPartyType");

        String loginId="1001";
        Integer h5Login=1;
        String userAgent="pc";
        String password="";

        CASUtils casUtils = new CASUtils();
        HttpSession session = request.getSession();
        String targetUrl = casUtils.getBasePath(request);
        /** 判断是否已经登录过 */
        if (casUtils.isLogin(session)) {
            //如果登录,重定向到targetUrl
            response.sendRedirect(targetUrl+"main");
            //如果没有登陆过
        } else {
            //判断票据是否存在
            if (casUtils.hasTicket(request)) {
                //存在就获取Cas登录Url 登录成功后返回票据 */
                LoginUser loginUser = casUtils.getLoginUser(request);
                //判断是否登录过
                if (loginUser.isLogin() ) {
                    /** 写入单页面登录判断标志 */
                    casUtils.login(loginUser, session);
                    String username = loginUser.getAccount();
                    CookiesUtil.setCookie(response,"redisSessionId",request.getSession().getId());
                    Cookie redisSessionCookie = new Cookie("redisSessionId",request.getSession().getId());
                    if (StringUtils.checkNull(loginId)) {
                        List<OrgManage> org = orgManageMapper.queryId();
                        if (org != null && org.size() > 0) {
                            loginId = org.get(0).getOid().toString().trim();
                        }
                    }


                    ToJson<Users> json = new ToJson<Users>(0, null);
                    if (StringUtils.checkNull(username)) {
                        json.setFlag(1);
                        json.setCode(LoginState.LOGINPASSWORDERR);
                        json.setMsg("用户名或用户不存在");
                        return json;
                    }
                    ContextHolder.setConsumerType("xoa" + loginId);
                    Users user = usersService.selectUserAllInfoByName(username, request, loginId, password, h5Login,thirdPartyType);
                    if (user == null) {
                        request.getSession().setAttribute("message", "errOne");
                        json.setMsg("用户名或用户不存在");
                        json.setCode(LoginState.LOGINPASSWORDERR);
                        json.setFlag(1);
                        return json;

                    }

                    List<SysPara> list = sysParaMapper.selectAll();
                    String pd = "";
                    String xts = "";
                    String cz = "";
                    for (SysPara sysPara : list) {
                        if ("SEC_RETRY_BAN".equals(sysPara.getParaName())) {
                            pd = sysPara.getParaValue();
                        }
                        if ("SEC_RETRY_TIMES".equals(sysPara.getParaName())) {
                            xts = sysPara.getParaValue();
                        }
                        if ("SEC_BAN_TIME".equals(sysPara.getParaName())) {
                            cz = sysPara.getParaValue();
                        }
                    }

                    Map<String, String> createMap = new HashMap<String, String>();
                    createMap.put("userid", username);
                    createMap.put("password", password);

                    //获取当前用户的登录日志
                    ToJson<Syslog> modifyPwdLog = sysLogService.getLoginLog(request);
                    if(user.getLastVisitTime()!=null){
                        user.setLastVisitTime(new Date());
                        usersService.updateLoginTime(user);
                    }else{
                        //判断他的size小于等于1，因为在查用户user信息时写入log日志的，因此第一次登录size为1
                        if (modifyPwdLog.getObj()==null||modifyPwdLog.getObj().size()<=1) {
                            json.setCode("FirstLogin");
                        } else {
                            user.setLastVisitTime(new Date());
                            usersService.updateLoginTime(user);
                        }
                    }

                    if (StringUtils.checkNull(loginId)) {
                        List<OrgManage> org = orgManageMapper.queryId();
                        if (org != null && org.size() > 0) {
                            loginId = org.get(0).getOid().toString().trim();
                        }
                    }
                    user.setCompanyId(loginId);
                    //判断用户头像
                    if(StringUtils.checkNull(user.getAvatar())){
                        if(!StringUtils.checkNull(user.getSex())){
                            user.setAvatar(user.getSex());
                        }else{
                            user.setAvatar("0");
                        }

                    }else{
                        if(user.getAvatar().equals("0")||user.getAvatar().equals("1")){
                            if(!StringUtils.checkNull(user.getSex())){
                                user.setAvatar(user.getSex());
                            }else{
                                user.setAvatar("0");
                            }
                        }
                        else{
                            //判断用户头像是否找得到
                            String classpath = this.getClass().getResource("/").getPath();
                            String webappRoot = classpath.replaceAll("WEB-INF/classes/", "ui/img/user/");
                            File file_avtor =new File(webappRoot+user.getAvatar());
                            if(!file_avtor.exists()){
                                user.setAvatar(user.getSex());
                            }
                        }
                    }
                    json.setObject(user);
                    json.setFlag(0);

                    //通过userId查询用户是否存在于静态map中
                    UserOnline userOnline = (UserOnline)userCountMap.get(user.getUserId());
                    //如果不存在
                    if(userOnline==null){
                        //声明一个新的用户在线数据
                        UserOnline userOnlineInfo =new UserOnline();
                        try {
                            String format = DateFormatUtils.formatDate(new Date());
                            Integer nowTime = DateFormatUtils.getNowDateTime(format);
                            userOnlineInfo.setClient((byte)2);
                            userOnlineInfo.setPCtime(nowTime);
                            userOnlineInfo.setPCsid(request.getSession().getId());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {//如果存在
                        if (!userOnline.getPCsid().equals("")) {
                            try {
                                String format = DateFormatUtils.formatDate(new Date());
                                Integer nowTime = DateFormatUtils.getNowDateTime(format);
                                userOnline.setPCtime(nowTime);
                                userCountMap.put(user.getUserId(), userOnline);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                String format = DateFormatUtils.formatDate(new Date());
                                Integer nowTime = DateFormatUtils.getNowDateTime(format);
                                userOnline.setPCtime(nowTime);
                                userOnline.setPCsid(request.getSession().getId());
                                userCountMap.put(user.getUserId(), userOnline);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("paraName", "IM_WINDOW_CAPTION");
                    params.put("paraValue", user.getPara().getParaValue());
                    params.put("loginDateSouse",loginId);//组织id
                    //params.put("LOCALE_SESSION_ATTRIBUTE_NAME", locales);//语言


                    String functionIdStr = userFunctionMapper.getUserFuncIdStr(user.getUserId());
                    params.put("functionIdStr", functionIdStr);

                    List<InterfaceModel> interfaceModels = sysInterfaceMapper.getInterfaceInfo();
                    if (0 == user.getTheme() || null == user.getTheme()) {
                        user.setTheme((byte) Integer.parseInt(interfaceModels.get(0).getTheme()));
                    }

                    String theme = "theme" + user.getTheme();
                    params.put("InterfaceModel", theme);
                    params.put("uid", user.getUid());
                    SessionUtils.putSession(request.getSession(), params,redisSessionCookie);

                    response.sendRedirect(targetUrl+"main");
                } else {
                    //重定向到 获取登出地址
                    response.sendRedirect(casUtils.getLogoutUrl(request));
                }
            } else {
                //票据不存在
                /** 获取登出地址 */
                String loginUrl = casUtils.getLoginUrl(request);
                //重定向到 获取登出地址
                response.sendRedirect(loginUrl);
            }
        }
        return null;
    }

}